// 引入http标准模块,CommonJS模块
const http = require("http");
const fs = require("fs");
const ws = require("socket.io");

// 创建一个web服务器
const server = http.createServer(function (request, response) {
    response.writeHead(200, {
        "Content-Type": "text/html;charset=UTF-8"
    });

    //// 读取文件
    const html = fs.readFileSync("../application/index/view/index/index.html");
    response.end(html);

});

// 基于当前web服务器开启socket实例
const io = ws(server);

// 检测连接事件
io.on("connection", function (socket) {



    let name = '';

    // 加入群聊
    socket.on("join", function (message) {
        name = message.username;
        io.emit("join", {
            type: 'join',
            name: name,
            count:message.count,
            user_list:message.user_list
        });
    });

    // 接收客户端所发送的信息
    socket.on("message", function (message) {
        console.log(message);
        // 向所有客户端广播发布的消息
        io.emit("message", {type: 'message', data: message});
    });

    //	 监听到连接断开
    socket.on("disconnect", function () {
        io.emit("disconnection", {
            type: 'out',
            name: name
        });
    });

});

// 服务器监听端口
server.listen(3000);
